<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">

<head>
    <th:block th:include="commons/css::css">head</th:block>
</head>

<body class="flat-blue">
<div class="app-container">
    <div class="row content-container">
        <th:block th:include="commons/nav_head::nav">head</th:block>
        <th:block th:include="commons/side::side">side</th:block>

        <div class="container-fluid">
            <div class="side-body">
                <div class="row">
                    <div class="col-xs-12">
                        <div class="panel panel-default">
                            <div class="panel-heading">
                                查询条件
                            </div>
                            <div class="panel-body form-group" style="margin-bottom:0px;">
                                <form>
                                    <label class="col-sm-1 control-label" for="searchRoleName"
                                           style="text-align: right; margin-top:5px">角色名称：</label>
                                    <div class="col-sm-2">
                                        <input type="text" class="form-control input-sm" id="searchRoleName" name="searchRoleName"/>
                                    </div>
                                    <div class="col-sm-2 col-sm-offset-1">
                                        <a href="javascript:void (0)" onclick="initTable()" class="btn btn-info btn-sm"><span
                                                class="fa fa-search"></span> 搜索</a>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <div id="toolbar" class="btn-group">
                            <shiro:hasPermission name="role_add">
                                <button id="btn_add" title="添加" type="button" class="btn btn-primary btn-sm" onclick="location.href = ctx + '/role/save_role_page/0'">
                                    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
                                </button>
                            </shiro:hasPermission>

                            <!--<shiro:hasPermission name="role_delete">
                                <button id="btn_delete" title="删除" type="button" style="margin-left: 4px" class="btn btn-sm btn-danger" onclick="deleteRole()">
                                    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
                                </button>
                            </shiro:hasPermission>-->
                        </div>

                        <table id="dataTable"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"
                        aria-hidden="true">×
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    权限控制
                </h4>
            </div>
            <div class="modal-body" id="permissionMonalBody">

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" id="modalCloseBtn"
                        data-dismiss="modal">关闭
                </button>
                <button type="button" class="btn btn-success" onclick="submitRolePermission()">
                    确定
                </button>
            </div>
        </div>
    </div>
</div>

<style>
    .modal-dialog {
        width: 800px;
    }
</style>
<th:block th:include="commons/js::js">Javascript Libs</th:block>
<script type="text/javascript">

    $(function () {
        $("#modalCloseBtn").click(function () {
            $("#permissionMonalBody :checkbox").prop("checked", false);
        });

        $("#dataTable").bootstrapTable({
            url: ctx + "/role/roleListPage", // 获取表格数据的url
            cache: false, // 设置为 false 禁用 AJAX 数据缓存， 默认为true
            striped: true,  //表格显示条纹，默认为false
            pagination: true, // 在表格底部显示分页组件，默认false
            pageList: [10, 20, 30, 50], // 设置页面可以显示的数据条数
            pageSize: 10, // 页面数据条数
            pageNumber: 1, // 首页页码
            sidePagination: 'server', // 设置为服务器端分页
            // toolbar: '#toolbar', // 工具按钮用哪个容器
            // showRefresh: true,
            silent: true,
            uniqueId: "id",
            undefinedText: "-",
            contentType: "application/x-www-form-urlencoded",
            method: "post",
            queryParams: function (params) { // 请求服务器数据时发送的参数，可以在这里添加额外的查询参数，返回false则终止请求
                return {
                    pageSize: params.limit, // 每页要显示的数据条数
                    offset: params.pageNumber, // 每页显示数据的开始行号
                    sort: params.sort, // 要排序的字段
                    sortOrder: params.order, // 排序规则
                    roleName: $("#searchRoleName").val()
                }
            },
            sortName: 'id', // 要排序的字段
            sortOrder: 'desc', // 排序规则
            columns: [
                {
                    checkbox: true, // 显示一个勾选框
                    align: 'center', // 居中显示
                    valign: "middle"
                }, {
                    field: 'id', // 返回json数据中的name
                    title: '编号', // 表格表头显示文字
                    align: 'center', // 左右居中
                    valign: 'middle', // 上下居中
                },{
                    field: 'roleName',
                    title: '角色名称',
                    align: 'center',
                    valign: 'middle',
                }, {
                    title: "操作",
                    align: 'center',
                    valign: 'middle',
                    width: 160, // 定义列的宽度，单位为像素px
                    formatter: function (value, row, index) {
                        var sb = new StringBuilder();
                        if (hasPermission("role_update")) {
                            sb.append('<button title="修改" class="btn btn-sm btn-info" onclick="updateRole(' + row.id + ')"><span class="glyphicon glyphicon-pencil"></span></button>&nbsp;&nbsp;');
                        }
                        if (hasPermission("role_saver_role_permission")) {
                            sb.append('<button title="权限设置" class="btn btn-sm btn-success" onclick="showRolesContainer(\''+row.roleCode+'\')"><span class="glyphicon glyphicon-wrench"></span></button>');
                        }
                        return sb.toString();
                    }
                }
            ],
            responseHandler: function (res) {
                return {
                    "rows": res.data.rows, // 具体每一个bean的列表
                    "total": res.data.total // 总共有多少条返回数据
                }
            }
        });

        $.get(ctx + "/role/selectAllPermissions", function (rtn) {
            var data = rtn.data;
            if (data != null && data.length > 0) {
                var sb = new StringBuilder();
                a: for (var i = 0; i < data.length; i++) {
                    var firstMenu = data[i];
                    sb.append('<div class="row" style="padding-left: 10px;background-color: #F0F0F0; line-height: 30px">')
                        .append('<label class="checkbox-inline"><input type="checkbox" value="'+firstMenu["menuCode"]+'" level="1" name="'+firstMenu["menuCode"]+'">' + firstMenu["menuName"] + "</label>")
                        .append("</div>");
                    var childMenus = data[i].childMenus;
                    if (childMenus == null || typeof childMenus == undefined) {
                        continue a;
                    }
                    b: for (var j = 0; j < childMenus.length; j++) {
                        var secondMenu = childMenus[j];
                        sb.append('<div class="row" style="padding-left: 30px; background-color: #F5F5F5; line-height: 30px;">')
                            .append('<label class="checkbox-inline"><input type="checkbox" value="'+secondMenu["menuCode"]+'" level="2" parent="'+firstMenu["menuCode"]+'" name="'+firstMenu["menuCode"]+"_"+secondMenu["menuCode"]+'">' + secondMenu["menuName"])
                            .append("</label></div>");
                        var permissions = secondMenu["permissions"];
                        if (permissions != null && permissions.length > 0) {
                            sb.append('<div class="row" style="padding-left: 50px; background-color: #FDFDFD; line-height: 30px">');
                        }
                        c: for (k = 0; k < permissions.length; k++) {
                            var permission = permissions[k];
                            sb.append('<label class="checkbox-inline">' + ' <input type="checkbox" value="'+permission["permissionCode"]+'" level="3" parent="'+firstMenu["menuCode"]+"_"+secondMenu["menuCode"]+'" name="'+firstMenu["menuCode"]+"_"+secondMenu["menuCode"]+"_"+permission["permissionCode"]+'">'+permission["permissionName"]+'</label>');
                        }
                        if (permissions != null && permissions.length > 0) {
                            sb.append('</div>');
                        }
                    }
                }
            }

            $("#permissionMonalBody").append(sb.toString());
            // 绑定事件
            $(":checkbox[level='1']").each(function (index, o) {
                $(o).on("click", function () {
                    var chkStatus = $(this).prop("checked");
                    var chkName = $(this).attr("name");
                    $(":checkbox[name^="+chkName+"]").prop("checked", chkStatus);
                });
            });
            $(":checkbox[level='2']").each(function (index, o) {
                $(o).on("click", function () {
                    // 判断下级是否选中
                    var chkName = $(this).attr("name");
                    $(":checkbox[name^="+chkName+"]").prop("checked", $(this).prop("checked"));
                    // 判断上级选中状态
                    var parent = $(this).attr("parent");
                    var level2ChkLength = $(":checkbox[name^="+parent+"_][level='2']:checked").length;
                    $(":checkbox[name="+parent+"]").prop("checked", level2ChkLength > 0);
                });
            });
            $(":checkbox[level='3']").each(function (index, o) {
                $(o).on("click", function () {
                    var parent = $(this).attr("parent");
                    // 设置第二级选中状态
                    var level3ChkLength = $(":checkbox[name^="+parent+"_][level='3']:checked").length;
                    var parentNode = $(":checkbox[name="+parent+"]");
                    parentNode.prop("checked", level3ChkLength > 0);

                    // 设置第一级选中状态
                    var rootName = parentNode.attr("parent");
                    var level2ChkLength = $(":checkbox[name^="+rootName+"][level='2']:checked").length;
                    $(":checkbox[name="+rootName+"]").prop("checked", level2ChkLength > 0);
                });
            });
        });
    });

    function initTable() {
        $("#dataTable").bootstrapTable("refresh");
    }

    function updateRole(roleId) {
        document.location.replace(ctx + "/role/save_role_page/" + roleId);
    }

    function deleteRole() {
        // 获取选中值
        var selectedChboxs = $("#dataTable").bootstrapTable('getSelections');
        console.info(selectedChboxs.length);
        if (selectedChboxs == null || selectedChboxs.length < 1) {
            Alert("请选择要操作的项");
            return;
        }
        var ids = [];
        for (var i = 0; i < selectedChboxs.length; i++) {
            ids.push(selectedChboxs[i].id);
        }
        Confirm("确认删除?", function () {
            $.post("/role/deleteRole", {ids:ids.join(",")}, function (rtn) {
                if (rtn.code != 1) {
                    Alert("操作失败");
                    return;
                }
                Alert("操作成功", function () {
                    document.location.replace(ctx + '/role/manager');
                });
            });
        })
    }

    var roleCode;
    function showRolesContainer(roleCode) {
        this.roleCode = roleCode;
        $("#myModal:checkbox").prop("checked", false);
        $.get(ctx + "/role/selectRoleMenuPermissions", {roleCode: roleCode}, function (rtn) {
            if (rtn && rtn.code == 1) {
                var data = rtn.data;
                for (var i = 0; i < data.length; i++) {
                    $(":checkbox[value="+data[i]+"]").prop("checked", true);
                }
            }
        });
        $('#myModal').modal("show")
    }

    function submitRolePermission() {
        if (!roleCode) {
            return;
        }
        // 获取选中的菜单权限
        var menus = $(":checkbox[level='1']:checked,:checkbox[level='2']:checked");
        var menuCodesArray = [];
        if (menus.length > 0) {
            menus.each(function (i, o) {
                menuCodesArray.push($(o).val());
            });
        }
        var permissions = $(":checkbox[level='3']:checked");
        var permissionCodesArray = [];
        if (permissions.length > 0) {
            permissions.each(function (i, o) {
                permissionCodesArray.push($(o).val());
            });
        }
        $.post(ctx + "/role/saveRolePermission", {menuCodes: menuCodesArray.join(","), permissionCodes: permissionCodesArray.join(","), roleCode: roleCode}, function (rtn) {
            if (rtn && (rtn.code == 1 || rtn.code == -1)) {
                Alert("操作成功", function () {
                    $("#myModal").modal("hide");
                    $("#permissionMonalBody :checkbox").prop("checked", false);
                    layer.closeAll();
                    if (rtn.code == -1) {
                        document.location.replace(ctx + "/logout")
                    }
                });
                return;
            }
            Alert("操作失败");
        });
    }


</script>
</html>